﻿// Scripts for Podcasting Solution for Microsoft Sharepoint

var categoryDisplayNames = new Array(
    new Array("PodcastDuration", "Time"),
    new Array("PodcastLanguage", "Language"),
    new Array("TargetedAudience", "Audience"),
    new Array("TargetedAudienceLevel", "Level")
);

function cbqFilter() {}
cbqFilter.prototype.Type;
cbqFilter.prototype.Column;
cbqFilter.prototype.Value;
cbqFilter.prototype.Operation;
cbqFilter.prototype.ColumnType;

var cbqPage = 1;

var otherQueryParams = new Array();

function addCategoryFilter(filterName, filterValue)
{
    // get the current url
    var href = getBaseLocation();
    var params = getQueryStringParams();    
    var foundItem = false;
    for(var i=1;i<params.length;i++)
    {
        if (params[i] == null) continue;
        if (params[i].Type == "filter" && params[i].Column.toLowerCase() == filterName.toLowerCase())
        {
            foundItem = true;
            if (params[i].ColumnType == "DateTime")
            {
                params[i].Value = CreateDateFilter(filterValue);
            }
            else
            {
                params[i].Value = filterValue;
            }
        }
    }    
    if (!foundItem)
    {
        if ("All Today ThisWeek ThisMonth ThisYear".indexOf(filterValue) > 0)
        {
            var item = new cbqFilter();
            item.Type = "filter";
            item.Column = filterName;
            item.Value = CreateDateFilter(filterValue);
            item.Operation = "Geq";
            item.ColumnType = "DateTime";
            var index = (params.length==0) ? 1 : params.length;
            params[index] = item;
        }
        else
        {
            var item = new cbqFilter();
            item.Type = "filter";
            item.Column = filterName;
            item.Value = filterValue;
            item.Operation = "Eq";
            item.ColumnType = "Text";
            var index = (params.length==0) ? 1 : params.length;
            params[index] = item;
        }
    }
    buildNewQueryString(params);
}

function getBaseLocation()
{
    return window.location.href.split(/\?/)[0];
}

function getQueryStringParams()
{
    var cbq = new Array();
    otherQueryParams = new Array();
    var qstring = window.location.href.split(/\?/)[1];
    if (qstring == null) return cbq;
        
    qstring = qstring.split(/\&/);
    for (var i=0;i<qstring.length;i++)
    {
        var param = qstring[i].substring(0,2);
        var index = (param=="sf" || param=="so") ? 0 : qstring[i].substring(2,3);
        var value = qstring[i].split(/=/)[1];
        
        if (cbq[index] == null) cbq[index] = new cbqFilter();
        
        switch (param.toLowerCase())
        {
            // Sort Params
            case "ff":
                cbq[index].Type = "filter";
                cbq[index].Column = value;
                break;
            case "fv":
                cbq[index].Value = value;
                break;
            case "fo":
                cbq[index].Operation = value;
                break;
            case "ft":
                cbq[index].ColumnType = value;
                break;
            // Sort Params
            case "sf":
                cbq[index].Type = "sort";
                cbq[index].Column = value;
                break;
            case "so":
                cbq[index].Value = value;
                break;
            case "pg":
                cbqPage= value;
                break;
            default:
                otherQueryParams[otherQueryParams.length] = qstring[i].split(/=/)[0] + "=" + value;
        }
    }
    return cbq;
}

function buildFilters(divName)
{
    // get the container
    var div = document.getElementById(divName);
    if (div == null) alert("Cannot create Filter Bar.");
    // build a nasty table
    var table = document.createElement("table");
    var tbody = document.createElement("tbody");
    var tr = document.createElement("tr");
    div.appendChild(table);
    table.appendChild(tbody);
    tbody.appendChild(tr);
    // create a cell
    var td = document.createElement("td");
    tr.appendChild(td);
    td.appendChild(document.createTextNode("Current Filter:"));
    
    var params = getQueryStringParams()
    // if there aren't any params
    if (params.length == 0)
    {
        // add a cell with the text "None"
        td = document.createElement("td");
        tr.appendChild(td);
        td.appendChild(document.createTextNode("None"));
        return;
    }
    else
    {
        for (var i = 0; i < params.length; i++)
        {
            if (params[i] == null) continue;
            if (params[i].Type != "filter") continue;
            // add a cell with the parameter's value
            td = document.createElement("td");
            tr.appendChild(td);
            
            var val;
            if (params[i].ColumnType == "DateTime")
            {
                val = GetFilterNameFromDate(params[i].Value);
            }
            else
            {
                val = params[i].Value;
            }
            val = lookupFilterDisplayName(params[i].Column) + " >> " + val;
            if (i != params.length-1) val += " /";
            
            td.appendChild(document.createTextNode(val));
            td.className = "am-filter-item";
            td.onmouseenter = function() { openFilterPopup(this); }; // popup options
            td.onmouseleave = function() { closeFilterPopup(this); }; // close popup
        }
    }
}

function lookupFilterDisplayName(title)
{
    var value = title;
    for (var i = 0; i < categoryDisplayNames.length; i++)
    {
        var namePair = categoryDisplayNames[i];
        if (namePair[0] == title)
        {
            value = namePair[1];
            break;
        }
    }
    return value;
}
function lookupFilterTitle(displayName)
{
    var value = displayName;
    for (var i = 0; i < categoryDisplayNames.length; i++)
    {
        var namePair = categoryDisplayNames[i];
        if (namePair[1] == displayName)
        {
            value = namePair[0];
            break;
        }
    }
    return value;
}

function openFilterPopup(item)
{    
    var div = document.createElement("div");
    var div2 = document.createElement("div");
    div2.appendChild(document.createTextNode("Remove"));
    div2.className = "am-filterPopup-text";
    
    div.className = "am-filterPopup";
    div.style.top = item.offsetHeight;
    div.style.left = 0;
    div.style.width = item.offsetWidth - 2;
    
    var text = item.innerText;
    text = text.replace(/\//, "");   // this is the regex for "/"
    text = text.split(/[ >> ]/);
    var filterName = lookupFilterTitle(text[0]);
    var filterValue = text[1];
    div.onclick = function() { removeCategoryFilter(filterName, filterValue); };
    
    div.appendChild(div2);
    item.appendChild(div);
    item.style.backgroundColor = "#666";
}

function closeFilterPopup(item)
{
    var divs = item.getElementsByTagName("div");
    for (var i=0;i<divs.length;i++) item.removeChild(divs[i]);
    item.style.backgroundColor = "black";
}

function removeCategoryFilter(filterName, filterValue)
{
    var href = getBaseLocation();
    var params = getQueryStringParams();
        
    for(var i=1;i<params.length;i++)
    {
        if (params[i] == null) continue;
        if (params[i].Column == filterName) params[i]=null;
    }
    buildNewQueryString(params);
}

function buildNewQueryString(params)
{
    var href = getBaseLocation();
    var pstring = "";
    var filterIndex = 1;
    for(var i=0;i<params.length;i++)
    {
        if (params[i] == null) continue;
        if (pstring.length==0) pstring += "?";
        else pstring += "&";
        
        if (params[i].Type == "filter")
        {
            pstring += "ff" + filterIndex + "=" + params[i].Column;
            pstring += "&fv" + filterIndex + "=" + params[i].Value;
            pstring += "&fo" + filterIndex + "=" + params[i].Operation;
            pstring += "&ft" + filterIndex + "=" + params[i].ColumnType;
            filterIndex++;
        }
        else if (params[i].Type == "sort")
        {
            pstring += "sf1=" + params[i].Column;
            pstring += "&so1=" + params[i].Value;
        }
    }
    if (pstring=="") pstring += "?pg=" + cbqPage;
    else if (pstring=="?") pstring += "pg=" + cbqPage;
    else pstring += "&pg=" + cbqPage;
    for(var i=0;i<otherQueryParams.length;i++)
    {
        pstring += "&" + otherQueryParams[i];
    }
    
    window.location = href + pstring;
}

function openSortDropdown(item)
{
	var divs=item.getElementsByTagName("div");
	var div;
	for(var i=0;i<divs.length;i++) if(divs[i].className=="am-grid-sortdropdown") div=divs[i];
	if(div==null)return;
	
	div.style.top = 24;
    div.style.left = 24;
    div.style.display = "block";
}

function closeSortDropdown(item)
{
	var divs=item.getElementsByTagName("div");
	var div;
	for(var i=0;i<divs.length;i++) if(divs[i].className=="am-grid-sortdropdown") div=divs[i];
	if(div==null)return;
	div.style.display = "none";
}

function sortGrid(sortType)
{
	// get the current url
    var href = getBaseLocation();
    var params = getQueryStringParams();    
    var foundItem = false;
    for(var i=0;i<params.length;i++)
    {
        if (params[i] == null) continue;
        if (params[i].Type == "sort")
        {
            foundItem = true;
            if (params[i].Column == sortType)
            {
                params[i].Value = (params[i].Value == "true") ? "false" : "true";
            }
            else
            {
                params[i].Column = sortType;
                params[i].Value = "true";
            }
        }
    }    
    if (!foundItem)
    {
        var item = new cbqFilter();
        item.Type = "sort";
        item.Column = sortType;
        item.Value = "true";
        var index = 0;
        params[index] = item;
    }
    buildNewQueryString(params);
}

function CheckPrevPageLink(senderId)
{   
    var sender = document.getElementById(senderId);
    var params = getQueryStringParams();
    if (cbqPage <= 1)
    {
        sender.style.display = "none";
    }
}

function NextPage()
{
    var params = getQueryStringParams();
    cbqPage++;
    buildNewQueryString(params);
}

function PrevPage()
{
    var params = getQueryStringParams();
    cbqPage--;
    if (cbqPage<=0) cbqPage=1;
    buildNewQueryString(params);
}

function CreateDateFilter(value)
{
    var date = new Date();
    switch(value)
    {
        case "All": date.setFullYear(1900,0,1); break;
        case "Today": /* Already set to Today */ break;
        case "ThisWeek": date.setDate(date.getDate() - date.getDay()); break;
        case "ThisMonth": date.setFullYear(date.getFullYear(), date.getMonth(), 1); break;
        case "ThisYear": date.setFullYear(date.getFullYear(), 0, 1); break;
    }
    return (date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() /*+ "T00:00:00Z"*/)
}

function GetFilterNameFromDate(value)
{
    var date = new Date();
    var dateStr;
    if (value.indexOf('T')>0) dateStr = value.substring(0, value.indexOf('T'));
    else dateStr = value;
    dateStr = dateStr.split('-');
    date.setFullYear(dateStr[0]);
    date.setMonth(dateStr[1]-1);
    date.setDate(dateStr[2]);
    
    if (date.getFullYear() == 1900) return "All";
    var today = new Date();
    if (date.toDateString() == today.toDateString()) return "Today";    
    var week = new Date();
    week.setDate(today.getDate() - today.getDay())
    if (date.toDateString() == week.toDateString()) return "This Week";
    var month = new Date();
    month.setFullYear(today.getFullYear(), today.getMonth(), 1);
    if (date.toDateString() == month.toDateString()) return "This Month";
    var year = new Date();
    year.setFullYear(today.getFullYear(), 1, 1);
    if (date.toDateString() == year.toDateString()) return "This Year";
    
    return value;
}

function CreateSortMarker(listId)
{
    var params = getQueryStringParams();
    var sortItem;
    var sortDir;
    for(var i=0;i<params.length;i++)
    {
        if (params[i] == null) continue;
        if (params[i].Type == "sort")
        {
            sortItem = params[i].Column;
            sortDir = params[i].Value;
            break;
        }
    }
    if (sortItem == null) return;
    
    var list = document.getElementById(listId);
    if (list==null) return;
    var li = list.getElementsByTagName("li");
    if (li==null || li.length==0) return;
    for(var i=0;i<li.length;i++)
    {
        var links = li[i].getElementsByTagName("a");
        if (links==null || links.length==0) continue;
        var link = links[0];
        var field = link.attributes["field"];
        if (field==null)continue;
        if (sortItem == field.value)
        {
            if (sortDir=="true")
            {
                var img = document.createElement("img");
                img.src = "/Style Library/PodcastingKit/Images/down_arrow.gif";
                img.alt = "ascending";
                img.style.paddingLeft = "4px";
                img.style.paddingBottom = "2px";
                img.style.border = "none";
                link.appendChild(img);
            }
            else
            {
                var img = document.createElement("img");
                img.src = "/Style Library/PodcastingKit/Images/up_arrow.gif";
                img.alt = "descending";
                img.style.paddingLeft = "4px";
                img.style.paddingBottom = "2px";
                img.style.border = "none";
                link.appendChild(img);
            }
        }
    }
    
}